const generator = require("@babel/generator");
const parser = require("@babel/parser");
const traverse = require("@babel/traverse");
const types = require("@babel/types");
const fs = require("fs");
const replacer = (path, cookiePartExpression) => {
    path.replaceWith(types.expressionStatement(
        types.assignmentExpression("=",
            types.memberExpression(types.identifier("window"), types.identifier("cookie")),
            cookiePartExpression
        )
    ))
}

function step1(ast) {
    traverse.default(ast, {
        AssignmentExpression(path) {
            // document[_0x2f91('0x97','y6QZ')+'ie']
            const { node } = path;
            if (types.isMemberExpression(node.left) && types.isIdentifier(node.left.object) && node.left.object.name === "document") {
                replacer(path, node.right)
            }
        }
    })
}


function step2(ast) {
    const visitor = {
        CallExpression(path) {
            // func(setTimeout)
            const node = path.node;
            let cookiePartExpression;
            if (
                node.arguments &&
                node.arguments[0] &&
                node.arguments[0].name === "setTimeout"
            ) {
                // 获取执行的函数体
                cookiePartExpression = node.arguments[1].body.body[0].expression.right

            }
            if (
                node.callee &&
                node.callee.name === "setTimeout"
            ) {
                cookiePartExpression = node.arguments[0].body.body[0].expression
            }
            if (cookiePartExpression) {
                replacer(path, cookiePartExpression)
            }

        }
    };
    traverse.default(ast, visitor)
}

function compile(code) {
    const ast = parser.parse(code);

    // traverse.default(ast, visitor);
    try {
        step1(ast);

    } catch (e) {}
    try {
        step2(ast)

    } catch (e) {}
    return generator.default(ast, {}, code).code;
}

// const code = fs.readFileSync("./pre.js", "utf-8");
// const output = compile(code);
// fs.writeFileSync("output.js", output)